package com.toulezu.test.outputformat;

import freemarker.core.CommonMarkupOutputFormat;
import freemarker.core.OutputFormat;
import freemarker.core.TemplateXMLOutputModel;
import freemarker.template.TemplateModelException;
import freemarker.template.utility.StringUtil;

import java.io.IOException;
import java.io.Writer;

public class SelfDefineOutputFormat extends CommonMarkupOutputFormat<TemplateXMLOutputModel> {

    /**
     * The only instance (singleton) of this {@link OutputFormat}.
     */
    public static final SelfDefineOutputFormat INSTANCE = new SelfDefineOutputFormat();

    /**
     * @since 2.3.29
     */
    protected SelfDefineOutputFormat() {
        // Only to decrease visibility
    }

    @Override
    public String getName() {
        return "Self";
    }

    @Override
    public String getMimeType() {
        return "Self";
    }

    @Override
    public void output(String textToEsc, Writer out) throws IOException, TemplateModelException {
        int writtenEnd = 0;  // exclusive end
        int ln = textToEsc.length();
        for (int i = 0; i < ln; i++) {
            char c = textToEsc.charAt(i);
            if (c == '\"') {
                int flushLn = i - writtenEnd;
                if (flushLn != 0) {
                    out.write(textToEsc, writtenEnd, flushLn);
                }
                writtenEnd = i + 1;

                switch (c) {
                    case '\"': out.write("\""); break;
                    default: break;
                }
            }
        }
        if (writtenEnd < ln) {
            out.write(textToEsc, writtenEnd, ln - writtenEnd);
        }
    }

    @Override
    protected TemplateXMLOutputModel newTemplateMarkupOutputModel(String plainTextContent, String markupContent) throws TemplateModelException {
        return null;
    }

    @Override
    public String escapePlainText(String plainTextContent) {
        return StringUtil.XMLEnc(plainTextContent);
    }

    @Override
    public boolean isLegacyBuiltInBypassed(String builtInName) {
        return builtInName.equals("xml");
    }


}
